Operator Precedence

When an expression contains multiple operators, their evaluation order follows precedence rules: higher precedence operators are evaluated first; if precedence is equal, evaluation proceeds left to right.

For example, in 1 + 2 * 3 - 4 / 2, multiplication and division have higher precedence than addition and subtraction, so they are evaluated first.

【Excel VBA】

Table 3-9 lists the precedence of major operators in Excel VBA.

Table 3-9 Operator Precedence in Excel VBA

Operator Description Precedence
( ) Parentheses 16 (highest)
x(i) Indexing 15
^ Exponentiation 14
~ Bitwise NOT 13
+/- Unary plus/minus 12
*, / Multiplication/division 11
\ Integer division 10
Mod Modulo 9
+, - Addition/subtraction 8
& String concatenation 7
=, <>, >, >=, <, <=, Like, New, TypeOf, Is, IsNot Comparison/identity 6
Not Logical NOT 5
And Logical AND 4
Or Logical OR 3
Xor Exclusive OR 2
Eqv Equivalence 1 (lowest)

【Python】

Table 3-10 lists the precedence of major operators in Python.

Table 3-10 Operator Precedence in Python

Operator Description Precedence
( ) Parentheses 18 (highest)
x[i] Indexing 17
x.attribute Attribute/method access 16
** Exponentiation 15
~ Bitwise NOT 14
+/- Unary plus/minus 13
*, /, //, % Multiplication/division/modulo 12

Continued Table 3-10

Operator Description Precedence
+, - Addition/subtraction 11
>>, << Bitwise shift 10
& Bitwise AND 9
^ Bitwise XOR 8
` ` Bitwise OR
==, !=, >, >=, <, <= Comparison 6
is, is not Identity 5
in, not in Membership 4
not Logical NOT 3
and Logical AND 2
or Logical OR 1 (lowest)

Examples of Precedence

Arithmetic Operations

Evaluate multiplication/division before addition/subtraction:

Excel VBA:

code.vba
Debug.Print 1 + 2 * 3 - 4 / 2  ' Output: 5

Python:

code.python
>>> 1 + 2 * 3 - 4 / 2

5.0 # Float result due to division

Parentheses Override Precedence

Use parentheses to change evaluation order:

Excel VBA:

code.vba
Debug.Print((1 + 2) * 3 - 4) / 2  ' Output: 2.5

Python:

code.python
>>> ((1 + 2) * 3 - 4) / 2
2.5

Relational and Logical Operations

Evaluate relational operations before logical operations:

Excel VBA:

code.vba
Debug.Print 3 > 2 And 7 < 5  ' Output: False

Python:

code.python
>>> 3 > 2 and 7 < 5
False

In the above example:

3 > 2 returns True, 7 < 5 returns False.

True and False returns False.